package com.zhou.common.lib.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author xianfeng
 * @date 2023/5/10 17:21
 */
@Slf4j
public class IoUtils {

    /**
     *
     *     response.setContentType("image/jpeg");
     *     response.setContentType("application/octet-stream;charset=UTF-8");
     *     content-disposition 指示如何处理响应内容。inline：直接在页面显示 attchment：以附件形式下载
     * @param content
     * @param response
     * @param contentType
     */
    public static void writeToResponse(byte[] content, HttpServletResponse response, String contentType, String contentDisposition) {
        if (StringUtils.isNotBlank(contentDisposition)) {
            response.setHeader("content-disposition", contentDisposition);
        }
        response.addHeader("Content-Length", "" + content.length);
        response.setContentType(contentType);
        try {
            ServletOutputStream out = response.getOutputStream();
            out.write(content);
            out.flush();
            out.close();
        } catch (IOException e) {
            log.error("", e);
        }
    }
}
